//
//  SevenTransition.swift
//  swiftTS
//
//  Created by 航电 on 2020/4/9.
//  Copyright © 2020 航电. All rights reserved.
//

import UIKit

enum SevenTransitionType:Int {
    case SevenTransitionType_Push = 0
    case SevenTransitionType_Pop
}

extension UIView {
    func imageFromView() -> UIImage {
        UIGraphicsBeginImageContextWithOptions(self.frame.size, false, UIScreen.main.scale);
        let context = UIGraphicsGetCurrentContext(); //该方法要放在UIGraphicsBeginImageContextWithOptions下面，不然获取为空
        self.layer.render(in: context!);
        var img = UIGraphicsGetImageFromCurrentImageContext();
        img = UIImage(cgImage: (img?.cgImage)!, scale: UIScreen.main.scale, orientation: .up);
        UIGraphicsEndImageContext();
        return img!;
    }
    
    func convertRectToWindow() -> CGRect {
        let window = UIApplication.shared.delegate?.window;
        let rect = self.convert(self.bounds, to: window!);
        return rect;
    }
}

class SevenTransition: NSObject {
    public var sevenType:SevenTransitionType = SevenTransitionType.SevenTransitionType_Push;
    public var _isAnimation:Bool = true;
    static let shardDefault = SevenTransition();
    
    class func transitionWithTransitionType(type:SevenTransitionType) ->SevenTransition {
        return SevenTransition().initWithTransition(type: type);
    }
    
    
    
    //TODO:Actions
    fileprivate func initWithTransition(type:SevenTransitionType) -> SevenTransition {
        
        self.sevenType = type;
        
        return self;
    }
    
    
    
    fileprivate func onPushAnimation(using transitionContext:UIViewControllerContextTransitioning) {
        let fromVC:SevenTransitionViewController = transitionContext.viewController(forKey: .from) as! SevenTransitionViewController;
        let toVC:SevenTransitionDetailViewController = transitionContext.viewController(forKey: .to) as! SevenTransitionDetailViewController;
        let containerView = transitionContext.containerView;
        _isAnimation = false;
        
        //初始化控件 界面上显示图
        let cell:UIImageView = UIImageView(frame: fromVC._selectCell.convertRectToWindow());
        cell.image = fromVC._selectCell.imageFromView();
        toVC.view.addSubview(cell);
        fromVC._selectCell.alpha = 0;
        containerView.addSubview(toVC.view);
        
        //动画效果
        let time = self.transitionDuration(using: transitionContext);
        
        //旋转
        let scale = (toVC._bgView?.frame.height)!/cell.frame.height;
        var transform3D = CATransform3DIdentity;
        transform3D.m34 = -1.0/1000.0;
        transform3D = CATransform3DRotate(transform3D, CGFloat.pi, 0, -1, 0);
        transform3D = CATransform3DScale(transform3D, scale, scale, 1);
        
        let animation = CABasicAnimation(keyPath: "transform");
        animation.duration = time/2;
        animation.toValue = NSValue(caTransform3D: transform3D);
        animation.timingFunction = CAMediaTimingFunction(name: .linear);
        animation.isRemovedOnCompletion = false;
        animation.fillMode = .both;
        animation.autoreverses = false;
        animation.beginTime = CACurrentMediaTime();
        cell.layer.add(animation, forKey: "transform_rotation");
        
        //位置
        let centerAnimation = CABasicAnimation(keyPath: "position");
        centerAnimation.duration = time;
        centerAnimation.beginTime = CACurrentMediaTime();
        centerAnimation.fromValue = NSValue(cgPoint: cell.center);
        centerAnimation.toValue = NSValue(cgPoint: toVC._bgView!.center);
        centerAnimation.fillMode = .both;
        centerAnimation.isRemovedOnCompletion = false;
        cell.layer.add(centerAnimation, forKey: "position");
        
        //旋转到一半就将背景隐藏
        DispatchQueue.main.asyncAfter(deadline: .now()+time/2/2) {
            cell.image = nil;
            cell.backgroundColor = .white;
        };
        
        toVC.onShowAnimation();
        
        //动画结束之后
        DispatchQueue.main.asyncAfter(deadline: .now()+time) {
            transitionContext.completeTransition(!transitionContext.transitionWasCancelled);
            self._isAnimation = true;
            if transitionContext.transitionWasCancelled {
                //转场失败
                cell.removeFromSuperview();
            } else {
                cell.removeFromSuperview();
                
                //push成功后 fromVC会消失，截屏当做toVC的背景
                let fromBgView = UIImageView(frame: fromVC.view.bounds);
                fromBgView.image = fromVC.view.imageFromView();
//                UIImageWriteToSavedPhotosAlbum(fromBgView.image!, nil, nil, nil);
                let fromView = UIView(frame: fromVC.view.bounds);
                fromView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.75);
                fromBgView.addSubview(fromView);
                toVC.view.addSubview(fromBgView);
                toVC.view.insertSubview(fromBgView, belowSubview: toVC._bgView!);
                
                //显示toVC的bgview
                toVC._bgView?.alpha = 1;
            }
        };
        
    }
    
    fileprivate func onPopAnimation(using transitionContext:UIViewControllerContextTransitioning) {
        let fromVC:SevenTransitionDetailViewController = transitionContext.viewController(forKey: .from) as! SevenTransitionDetailViewController;
        let toVC:SevenTransitionViewController = transitionContext.viewController(forKey: .to) as! SevenTransitionViewController;
        let containView = transitionContext.containerView;
        _isAnimation = false;
        //添加界面上显示图
        containView.addSubview(toVC.view);
//        containView.addSubview(fromVC.view);
        
        let cell = fromVC._bgView?.snapshotView(afterScreenUpdates: false);
        cell?.frame = (fromVC._bgView?.convertRectToWindow())!;
        cell?.layer.zPosition = 9999;
        containView.addSubview(cell!);
        containView.bringSubviewToFront(cell!);
        fromVC._bgView?.alpha = 0;
        toVC._selectCell.alpha = 0;
        let imgView = UIImageView(frame: cell!.bounds);
        cell?.addSubview(imgView);
        imgView.tag = 999;
        imgView.alpha = 0;
        
        let time = self.transitionDuration(using: transitionContext);
        
        //旋转
        let scale = toVC._selectCell.frame.height/(fromVC._bgView?.frame.height)!;
        var transform3D = CATransform3DIdentity;
        transform3D.m34 = -1.0/1000.0;
        transform3D = CATransform3DRotate(transform3D, CGFloat.pi, 0, 1, 0);
        transform3D = CATransform3DScale(transform3D, scale, scale, 1);
        
        let animation = CABasicAnimation(keyPath: "transform");
        animation.duration = time/2;
        animation.beginTime = CACurrentMediaTime();
        animation.fillMode = .forwards;
        animation.toValue = NSValue(caTransform3D: transform3D);
        animation.isRemovedOnCompletion = false;
        animation.autoreverses = false;
        cell?.layer.add(animation, forKey: "to_transform");
        
        //位置
        let toRect = toVC._selectCell.convertRectToWindow();
        let centerAnimation = CABasicAnimation(keyPath: "position");
        centerAnimation.beginTime = CACurrentMediaTime();
        centerAnimation.duration = time;
        centerAnimation.fromValue = NSValue(cgPoint: fromVC._bgView!.center);
        centerAnimation.toValue = NSValue(cgPoint: CGPoint(x: toRect.midX, y: toRect.midY));
        centerAnimation.fillMode = .forwards;
        centerAnimation.isRemovedOnCompletion = false;
        centerAnimation.autoreverses = false;
        cell?.layer.add(centerAnimation, forKey: "to_positon");
        
        DispatchQueue.main.asyncAfter(deadline: .now()+time/2/2) {
            let imgView:UIImageView = cell?.viewWithTag(999) as! UIImageView;
            imgView.image = toVC._selectCell._bgView.imageFromView();
            imgView.alpha = 1;
            imgView.layer.transform = CATransform3DMakeRotation(CGFloat.pi, 0, 1, 0);
        };
            
        //完成动画后
        DispatchQueue.main.asyncAfter(deadline: .now()+time) {
            transitionContext.completeTransition(!transitionContext.transitionWasCancelled);
            self._isAnimation = true;
            if transitionContext.transitionWasCancelled {
                cell?.removeFromSuperview();
            } else {
                cell?.removeFromSuperview();
                toVC._selectCell.alpha = 1;
                toVC._mainCollectionView.isScrollEnabled = true;
    //            toVC.viewDidAppear(true);
            }
        };
    }
}

extension SevenTransition:UIViewControllerAnimatedTransitioning {
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        if self.sevenType == SevenTransitionType.SevenTransitionType_Push {
            return 0.8;
        }
        else if self.sevenType == SevenTransitionType.SevenTransitionType_Pop {
            return 0.8;
        }
        return 0;
    }

    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        switch self.sevenType {
        case SevenTransitionType.SevenTransitionType_Push:
            self.onPushAnimation(using: transitionContext);
            break
        case SevenTransitionType.SevenTransitionType_Pop:
            self.onPopAnimation(using: transitionContext);
            break
        
        }
    }
}
